import fs from 'fs';
import url from 'url';
import { GetFilePath } from './getPath.js';

function readContorller(controllerPath) {
	console.log(`readContorller:${controllerPath}`);
	let fullCPath = GetFilePath(controllerPath)
	console.log(`readContorller:${fullCPath}`);

	if (fs.existsSync(fullCPath)) {

		const jsPath = fs.readdirSync(fullCPath).filter(file => file.endsWith("js")).map(item => `${fullCPath}/${item}`)
		return jsPath;
	} else {
		console.log(`readContorller: 不存在路径${fullCPath}`);
		return null;
	}
}

function redistyRouter(Router, fullJsPath) {
	console.log(`redistyRouter:${fullJsPath}`)

	fullJsPath.forEach(async (contorller) => {
		const controllerUsers = (await import(contorller)).object

		for (const UK in controllerUsers) {
			// console.log(`UK:${UK}`);

			const [method, requestPath] = UK.split('@');
			console.log(`method:${method}`);
			
			const requestFn = controllerUsers[UK];
			// console.log(`requestFn:${requestFn}`);

			if (method.endsWith("get")) {
				Router.get(requestPath, requestFn);
			} else if (method.endsWith("post")) {
				Router.get(requestPath, requestFn);
			} else if (method.endsWith("put")) {
				Router.put(requestPath, requestFn)
			} else if (method.endsWith("delete")) {
				Router.delete(requestPath, requestFn)
			} else {
				console.error(`${method}：请求方式不正确`);
			}

		}
	})
}
export const ReadContorller = readContorller;
export const RedistyRouter = redistyRouter;